#include "thread-utils.h"

int binary_search(pthread_t thread, pthread_t *thread_pool, int a, int b)
{
    int mid;
    if (thread_pool[a] == thread)
        return a;
    else if (thread_pool[b] == thread)
        return b;
    else if (b <= a)
        return -1;
    mid = b + (b-a)/2;
    if (thread_pool[mid] > thread)
        return binary_search(thread, thread_pool, a+1, mid);
    else if (thread_pool[mid] < thread)
        return binary_search(thread, thread_pool, mid, b-1);
    else
        return mid;
}


pthread_t thread_pool_remove(pthread_t t, pthread_t *thread_pool, int n)
{
    int i;
    int index;
    pthread_t aux;

    index = binary_search(t, thread_pool, 0, n-1);

    if (index == -1)
        return 0;

    aux = thread_pool[index];
    for (i = index; i < n-1; i++)
    {
        thread_pool[i] = thread_pool[i+1];
    }
    return aux;
}

void insertion_sort(pthread_t v[], int n)
{
    int i, j, key;

    for (j=1; j<n; j++)
    {
        key = (int) v[j];
        i = j-1;
        while (i >= 0 && ((int)v[i]) > key)
        {
            v[i+1] = v[i];
            i--;
        }
        v[i+1] = (pthread_t) key;
    }
}

void thread_pool_insert(pthread_t t, pthread_t *thread_pool, int n)
{
    thread_pool[n] = t;
    insertion_sort(thread_pool, n+1);
}

